package com.beiing.tianshuai.tianshuai.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.ImagePreviewViewPagerAdapter;
import com.lzy.ninegrid.preview.HackyViewPager;

import java.text.MessageFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Create by 杨金达
 * 支持多图片预览的Fragment
 */
public class ImagePreviewFragment extends Fragment {


    @BindView(R.id.viewPager)
    HackyViewPager mViewPager;
    @BindView(R.id.tv_pager)
    TextView mTvPager;
    @BindView(R.id.rootView)
    RelativeLayout mRootView;

    private Context                             mContext;
    private Unbinder                            mUnbinder;
    private ImagePreviewViewPagerAdapter        mAdapter;

    public static ImagePreviewFragment newInstance(ArrayList<String> imageUrls) {
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("urls", imageUrls);
        ImagePreviewFragment fragment = new ImagePreviewFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image_preview, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        mContext = getActivity();
        Bundle arguments = getArguments();
        final ArrayList<String> urls = arguments.getStringArrayList("urls");
        if (urls != null) {
            mAdapter = new ImagePreviewViewPagerAdapter(mContext, urls);
            mViewPager.setAdapter(mAdapter);
            mViewPager.setCurrentItem(0);
            mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    mTvPager.setText(MessageFormat.format("{0}/{1}", position + 1, urls.size()));
                }
            });
            mTvPager.setText(MessageFormat.format("1/{0}", urls.size()));
        }
        onDestroy();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }
}
